package com.ruoyi.web.controller.projectAch;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.projectAch.domain.WebPages;
import com.ruoyi.projectAch.mapper.WebPagesMapper;
import com.ruoyi.projectAch.service.IWebPagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * 附件信息，用于存储网页和相关文件的信息Controller
 *
 * @author ruoyi
 * @date 2023-11-07
 */
@RestController
@RequestMapping("/projectAch/pages")
public class WebPagesController extends BaseController {
    @Autowired
    private IWebPagesService webPagesService;

    @Autowired
    RuoYiConfig RuoYiConfig;

    @Autowired
    WebPagesMapper webPagesMapper;

    /**
     * 查询附件信息，用于存储网页和相关文件的信息列表
     */
    @PreAuthorize("@ss.hasPermi('projectAch:pages:list')")
    @GetMapping("/list")
    public TableDataInfo list(WebPages webPages) {
        startPage();
        List<WebPages> list = webPagesService.selectWebPagesList(webPages);
        return getDataTable(list);
    }

    /**
     * 导出附件信息，用于存储网页和相关文件的信息列表
     */
    @PreAuthorize("@ss.hasPermi('projectAch:pages:export')")
    @Log(title = "附件信息，用于存储网页和相关文件的信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WebPages webPages) {
        List<WebPages> list = webPagesService.selectWebPagesList(webPages);
        ExcelUtil<WebPages> util = new ExcelUtil<WebPages>(WebPages.class);
        util.exportExcel(response, list, "附件信息，用于存储网页和相关文件的信息数据");
    }

    @CrossOrigin
    @Anonymous
    @GetMapping("/xinAdd")
    public String fun(@RequestParam String url) {
        System.out.println("执行了----------------------" + url);
        WebPages webPages = new WebPages();
        webPages.setUrl(url);
        webPages.setStatus("downloading");
        webPages.setTitle("加载中...");
        toAjax(webPagesService.insertWebPages(webPages));
        return "任务执行中，请稍后";
    }

    @CrossOrigin
    @Anonymous
    @GetMapping("/xinQuery")
    public WebPages query(@RequestParam String url) {
        WebPages webPages = webPagesMapper.selectByURL(url);
        System.out.println(webPages);
        return webPages;
    }

    /**
     * 根据文件名下载指定的文件。
     */
    @GetMapping("/downloadZip")
    public void fileDownload(@RequestParam String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            System.out.println("进入下载函数:  " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime()));
            System.out.println("文件名称：" + fileName);
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            System.out.println("开始写入发送文件时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime()));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.format("下载文件失败", e);
        }
        System.out.println("结束写入发送文件时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime()));
    }

    /**
     * 获取附件信息，用于存储网页和相关文件的信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('projectAch:pages:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(webPagesService.selectWebPagesById(id));
    }

    /**
     * 新增附件信息，用于存储网页和相关文件的信息
     */
    @PreAuthorize("@ss.hasPermi('projectAch:pages:add')")
    @Log(title = "附件信息，用于存储网页和相关文件的信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WebPages webPages) {
        webPages.setStatus("downloading");
        webPages.setTitle("加载中...");
        return toAjax(webPagesService.insertWebPages(webPages));
    }

    /**
     * 修改附件信息，用于存储网页和相关文件的信息
     */
    @PreAuthorize("@ss.hasPermi('projectAch:pages:edit')")
    @Log(title = "附件信息，用于存储网页和相关文件的信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WebPages webPages) {
        return toAjax(webPagesService.updateWebPages(webPages));
    }

    /**
     * 删除附件信息，用于存储网页和相关文件的信息
     */
    @PreAuthorize("@ss.hasPermi('projectAch:pages:remove')")
    @Log(title = "附件信息，用于存储网页和相关文件的信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(webPagesService.deleteWebPagesByIds(ids));
    }
}
